from settings import Settings
import logging,os
from wombat import WombatRequestHandler, WombatDefaultRequestHandler, send_mail
from users.businesses.views import FindHeadOfficeRequestHandler
from google.appengine.ext import db
from users.businesses.models import BusinessLocation, PosDevice,ReceiptEmailLayout,ReceiptLayout,Company
from users.businesses.advertising.models import AdvertisingCampaign
from yengine import controller

class UserHandler(WombatRequestHandler):

  @controller
  def get(self,action=None):
    self.session['login_referrer']='/users/businesses/pos_device?'+self.request.query_string
    if self.request.get('device_description'):
      self.session['device_key'] =self.request.get('device_description')
    try:
      super(UserHandler, self).get(action)
    except Exception,e:
      logging.exception(e)
    if 'user_key' in self.session and self.request.get('device_description'):
      if db.get(self.session['user_key']):
        logging.info("user already created, redirecting home page")
        self.redirect('/users/businesses/pos_device?' + self.request.query_string)
      else:
        logging.warn('user was in session but not in db')
        del session['user_key']

  @controller
  def post(self,action=None):
    #self.request.path = '/wombat/user'
    super(UserHandler, self).post(action, _redirect=False)
    new_user = self.posted_entity
    if new_user:
      service_account_key = self.request.get('service_account_key')
      if service_account_key:
        service_account = db.get(service_account_key)
        if service_account:
          new_user.add_scope(service_account)
          new_user.type = 'manager'
          new_user.put()
      logging.info('user created, about to redirect to /account')
      self.session['allowed_user_key'] = str(new_user.key())
      self.session['user_key'] = str(new_user.key())
      self.redirect('/account?user_key='+str(new_user.key())+'&'+self.request.query_string)
    else:
      logging.info('invalid user posted')

class AccountHandler(WombatRequestHandler):

  '''def get(self,action=None):
    super(AccountHandler,self).get(action)'''

  def post(self,action=None):
    logging.info('Posting AccountRequestHandler')
    self.service_account = None
    #self.request.path = '/wombat/user'
    super(AccountHandler, self).post(action, _redirect=False)
    new_account = self.posted_entity
    if new_account:
      self.response.headers.add_header('x-yreceipts-account-key', str(new_account.key()))
      self.response.headers.add_header('x-yreceipts-auth-key', new_account.auth_key)
      service_account_key = self.request.get('service_account_key')
      if service_account_key:
        self.service_account = db.get(service_account_key)
        if self.service_account:
          new_account.add_scope(self.service_account)
          new_account.put()
      logging.info('account created')
      ho = self.create_head_office(new_account)
      self.response.headers.add_header('x-yreceipts-company-key', str(ho.key()))
      bl = self.create_business_location(ho,new_account)
      self.response.headers.add_header('x-yreceipts-businesslocation-key', str(bl.key()))
      pos = self.create_pos_device(bl,new_account)
      self.response.headers.add_header('x-yreceipts-posdevice-key', str(pos.key()))
      #ad = self.create_new_ad_campaign(ho,new_account)
      #receipt_layout = ho.get_receipt_layout()
      #receipt_layout.left_margin = -1.0
      #receipt_layout.background_model = '1_IMAGE'
      #receipt_layout.right_margin = -1.0
      #receipt_layout.draw_inner_frame = True
      #receipt_layout.typeface = 'Courier New'#'Arial'
      #image_path = os.path.join( os.path.dirname(__file__),"..","adds","background.jpg")
      #image_file = open(image_path,"rb")
      #image = image_file.read()
      #receipt_layout.background_image = image
      #receipt_layout.put()
      #email_layout = ho.get_receipt_email_layout()
      #receipt_layout = self.create_new_reecipt_template(new_account)
      user_key = self.request.get('user_key')
      if user_key:
        logging.info('user_key provided [%s], assigning the new account to the user' % user_key)
        user = db.get(user_key)
        if not user:
          logging.info('could not resolve user_key to an entity')
        else:
          user.account = new_account
          user.put()
          if 'allowed_user_key' in self.session:
            if str(user.key()) == self.session['allowed_user_key']:
              self.session['user_key'] = self.session['allowed_user_key']
            del self.session['allowed_user_key']
      else:
        logging.info('no user_key provided')
      if len(self.session['messages']) == 1:
        self.session['messages'] = []
      self.session['messages'].append('''<span style="color: #0E416D;">Registration completed. You're ready to send email receipts.</span>''')
      self.redirect('/users/businesses/pos_device/')
    else:
      logging.info('invalid account posted')

  def modify_data(self):
    if 'form' in self.template_values and 'device_description' in self.template_values['form']._fields:
      if not self.template_values['form']._fields['device_description'].data:
        if self.request.get('device_key'):
          self.template_values['form']._fields['device_description'].data = self.request.get('device_key')
        elif 'device_key' in self.session:
          self.template_values['form']._fields['device_description'].data = self.session['device_key']


  def create_new_email_template(self,ho,new_account):
    email_template = ReceiptEmailLayout(business_location=ho,name=self.request.get('name') + ' receipt template')
    email_template.add_scope(new_account)
    if self.service_account:
      new_account.add_scope(self.service_account)
    email_template.put()

  def create_new_reecipt_template(self,new_account):
    logging.info("creating new receipt template ")
    receipt_template = ReceiptLayout(name=self.request.get('name') + ' receipt template')
    receipt_template.add_scope(new_account)
    receipt_template.top_text_padding = 0.0
    receipt_template.left_margin = -1.0
    receipt_template.background_model = '1_IMAGE'
    receipt_template.right_margin = -1.0
    receipt_template.draw_inner_frame = True
    receipt_template.typeface = 'Courier New'#'Arial'
    image_path = os.path.join( os.path.dirname(__file__),"..","adds","background.jpg")
    image_file = open(image_path,"rb")
    image = image_file.read()
    receipt_template.background_image = image
    if self.service_account:
      new_account.add_scope(self.service_account)
    receipt_template.put()


  def create_new_ad_campaign(self,ho,new_account):
    ad = AdvertisingCampaign(business_location=ho,name = self.request.get('name') + ' ad campaign')
    ad.add_scope(new_account)
    if self.service_account:
      new_account.add_scope(self.service_account)
    ad.put()

  def create_head_office(self, account):
    store_name = self.request.get('name')
    ho = Company(store_name=store_name)
    ho.add_scope(account)
    if self.service_account:
      ho.add_scope(self.service_account)
    try:
      el = db.get('ahBzfnlyZWNlaXB0cy1wcm9kchsLEhJSZWNlaXB0RW1haWxMYXlvdXQY6JeRCQw').get_clone(name=str(ho) + ' email template')
      el.add_scope(account)
      el.put()
      self.insert_into_mysql(el)
      ho.receipt_email_layout = el
    except Exception, e:
      logging.exception(e)
    try:
      rl = db.get('ahBzfnlyZWNlaXB0cy1wcm9kchYLEg1SZWNlaXB0TGF5b3V0GNzoiQkM').get_clone(name=str(ho) + ' receipt template')
      rl.add_scope(account)
      rl.put()
      self.insert_into_mysql(rl)
      ho.receipt_layout = rl
    except Exception, e:
      logging.exception(e)
    ho.business_name = self.request.get('name')
    #ho.hidden=True
    ho.put()
    self.insert_into_mysql(ho)
    return ho

  def create_business_location(self, ho,account):
    store_name = self.request.get('store_name')
    bl = BusinessLocation(store_name = store_name)
    bl.bl_head_office = ho
    bl.email_address = self.request.get('store_email')
    bl.address_line_one = self.request.get('store_address_line_one')
    bl.address_line_two = self.request.get('store_address_line_two')
    bl.add_scope(account)
    if self.service_account:
      bl.add_scope(self.service_account)
    bl.put()
    self.insert_into_mysql(bl)
    return bl

  def create_pos_device(self, bl,account):
    device_description = self.request.POST.get('device_description') or self.request.get('device_description')
    key_name = self.request.get('PosDevice.key_name')
    if key_name:
      pos = PosDevice(device_description = device_description, key_name=key_name)
    else:
      pos = PosDevice(device_description = device_description)
    pos.business_location = bl
    if 'device_key' in self.session:
      pos.device_key = self.session['device_key']
      del self.session['device_key']
    pos.add_scope(account)
    if self.service_account:
      pos.add_scope(self.service_account)
    pos.put()
    self.insert_into_mysql(pos)
    return pos


class AuthCodeRequestHandler(WombatDefaultRequestHandler):
  path = '/auth_code'

  def render_template(self):
    jinja_environment = Settings.template_environment
    template = jinja_environment.get_template('auth_code.jade')
    response_str = template.render(self.template_values)
    self.response.out.write(response_str)

  def get(self):
    user = self.current_user
    code = user.get_auth_code()
    sender = 'yReceipts <customer.service@yreceipts.com>'
    recipient = user.email
    subject = 'Your authentication code'
    body = '%s\n\nThis code is valid for 10 minutes from the moment it was requested.' % str(code)
    send_mail(sender, recipient, subject, body, bcc='teamyr@yreceipts.com')

    self.render_template()

  def post(self):
    user = self.current_user
    code = self.request.get('code')
    if user.is_auth_code_valid(code):
      long_term = bool(self.request.get('long_term'))
      token = user.get_auth_token(code, long_term=long_term)

      self.response.set_cookie(
        user.get_auth_token_cookie_name(),
        str(token),
        max_age=60*60*24*365
      )
      self.redirect(self.user_login_path)
    else:
      self.template_values['code_invalid'] = True
      self.render_template()
